var lodash = require('lodash');

var utils = require('../utils');
import { Dao } from "./dao-service";

function Uploads() {
    Dao.apply(this, ['uploads']);
    // Dao('uploads', null);  
}

function getPackId(url) {
    var packId = null;
    var dirs = url.split('/');
    var index = lodash.indexOf(dirs, 'sync-packages');
    if (index > -1) {
        packId = dirs[index + 1];
    }
    return packId;
}


Uploads.prototype.newUpload = function (url, headers, body) {
    var packed = headers['mpj-sync-packed'];
    var upload = {
        id: body.id,
        version: headers['mpj-sync-resource-version'],
        packId: packed ? packed : null,
        syncpkg: packed ? null : getPackId(url),
        url: url,
        headers: lodash.extend(lodash.pick(headers, [
            'mpj-sync-time-expire',
            'mpj-sync-resource-version',
            'mpj-sync-packed',
            'mpj-sync-terminal-bind-id',
            'cookie']), { 'Content-Type': headers['content-type'], 'Authorization': headers['authorization'], 'Cookie': headers['cookie'] }),
        body: body,
        createTime: new Date().getTime()
    };
    
    upload.headers.token = headers.token;
    return Promise.resolve(upload);
};

Uploads.prototype.saveUploads = function (url, params, headers, body) {
    if (!body.id) {
        throw new Error(JSON.stringify({ mess: 'put no id', url: url, headers: headers, body: body }));
    }

    var self = this;
    var version = headers['mpj-sync-resource-version'];
    var promise = version ? this.datastore.get({ id: body.id, version: version }) : Promise.resolve();
    return promise.then(function (oldUpload) {
        // 存在就不再保存了,不知道会不会有问题
        if (!oldUpload) {
            return self.newUpload(url, headers, body).then(function (upload) {
                return self.datastore.insert(upload);
            });
        }
    });
};

Uploads.prototype.queryAll = function () {
    var find = this.datastore.datastore.find({ packId: null }).sort({ createTime: 1 });
    return (<any>Promise).promisify(find.exec.bind(find))();
};

Uploads.prototype.queryChildren = function (packId) {
    var find = this.datastore.datastore.find({ packId: packId }).sort({ createTime: 1 });
    return (<any>Promise).promisify(find.exec.bind(find))();
};

module.exports = new Uploads();
